

require('state')

require('algo.lazzyJohn')
require('algo.boom')
require('algo.pullUp')
require('algo.bombastic')
require('algo.fantastic')
require('algo.algoasc')
require('algo.algotator')
require('algo.fromuptodown')
require('algo.johnDoe')
require('algo.giantbuy')
require('algo.megabuy')
require('algo.hyperbuy')

Pool = {}

Pool.STATE = NORMAL
Pool.algos = {}
Pool.simulation = {}
Pool.current = nil
Pool.nbCycles = 20
Pool.currentCycle = 0

function Pool:init()
   table.insert(Pool.algos, lazzyJohn)
   table.insert(Pool.algos, boom)
   table.insert(Pool.algos, bombastic)
   table.insert(Pool.algos, fantastic)
   table.insert(Pool.algos, algoasc)
   table.insert(Pool.algos, algotator)
   table.insert(Pool.algos, pullUp)
   table.insert(Pool.algos, fromuptodown)
   table.insert(Pool.algos, johnDoe)
   table.insert(Pool.algos, giantbuy)
   table.insert(Pool.algos, megabuy)
   table.insert(Pool.algos, hyperbuy)
   Pool:resetSimu()
end

function Pool:update()
   Pool.currentCycle = Pool.currentCycle + 1
   if Anal.day == 0 then
      io.write("sell " .. Anal.nb_action .. "\n")
      io.flush()
   else
      if Pool.current == nil then Pool.current = 1 end
      for i,j in ipairs(Pool.algos) do
	 if i ~= Pool.current then j:update(Pool.simulation[i], Simulate) end
      end
      Pool.algos[Pool.current]:update(Pool.simulation[Pool.current], Action)
   end

   if  Pool.currentCycle > 10 and (Pool.current ~= Pool:getBetterAlgo()) then
      Pool.current = Pool:getBetterAlgo()
      Pool.currentCycle = 0
      Pool:resetSimu()
      log:write("Fin du cycle, nouveau algo : " .. Pool.current .. " : " .. Pool.algos[Pool.current].name .. "\n")
   end
   if Pool.currentCycle >= Pool.nbCycles then
      Pool.current = Pool:getBetterAlgo()
--      if Anal.money + (Anal.nb_action * Anal.current) - (Anal.nb_action * Anal.current) * 0.15 / 100 < Anal.money_start then Pool.current = 1; log:write("DETRESSE!\n") end
      Pool.currentCycle = 0
      Pool:resetSimu()
      log:write("Fin du cycle, nouveau algo : " .. Pool.current .. " : " .. Pool.algos[Pool.current].name .. "\n")
   end   

end

function Pool:getBetterAlgo()
   local res = 1
   local max = 0
   local tmp = 0

   for i,j in ipairs(Pool.algos) do
      tmp = Pool.simulation[i].money + (Pool.simulation[i].nb_action * Anal.les) - (Pool.simulation[i].nb_action * Anal.les) * 0.15 / 100
      if tmp > max then res = i; max = tmp end
   end
   return (res)
end

function Pool:resetSimu()
   for i,j in ipairs(Pool.algos) do
      Pool.simulation[i] = Simulation:create(Anal.money, Anal.nb_action)
   end
end